//#include"ArrayList.hpp"

#include <malloc.h>

template <class T>
class ArrayList
{
public:
	ArrayList();
	~ArrayList();
	void add(T t);
	T get(int index);
	int size();
	T remove(int index);
private:
	int index = 0;
	int len = 10;
	T* arr;
	void resizeArr();
};

/**
 * 创建的时候分配相应的空间
 * @tparam T
 */
template <class T>
ArrayList<T>::ArrayList()
{
	this->arr = (T*)malloc(sizeof(T) * this->len);
}

/**
 * 释放的时候将相应的空间一起释放
 * @tparam T
 */
template <class T>
ArrayList<T>::~ArrayList()
{
	if (this->arr != NULL) {
		free(this->arr);
	}
}

/**
 * 当长度不够的时候重新设置长度
 * @tparam T
 */
template <class T>
void ArrayList<T>::resizeArr()
{
	T * newArr = (T*)malloc(sizeof(T) * this->len);
	for (int i = 0; i < this->index; i++) {
		newArr[i] = this->arr[i];
	}
	free(this->arr);
	this->arr = NULL;
	this->arr = newArr;
}

/**
 * 添加元素
 * @tparam T
 * @param t
 */
template <class T>
void ArrayList<T>::add(T t)
{
	if (this->index < this->len) {
		this->arr[this->index] = t;
		this->index++;
	}
	else
	{
		this->len = this->len + (this->len >> 1); //长度变为原来长度的1.5倍（右移一位相当于除以2）
		this->resizeArr();
		this->add(t);
	}
}

/**
 * 获取元素
 * @tparam T
 * @param index
 * @return
 */
template <class T>
T ArrayList<T>::get(int index)
{
	if (this->index > index) {
		return this->arr[index];
	}
	else {
		return NULL;
	}
}

/**
 * 获取集合的大小
 * @tparam T
 * @return
 */
template <class T>
int ArrayList<T>::size() {
	return this->index;
}

/**
 * 移除并返回被移除的元素
 * @tparam T
 * @param index
 * @return
 */
template <class T>
T ArrayList<T>::remove(int index) {
	if (index >= this->index) {
		return NULL;
	}
	else {
		T t = this->arr[index];
		for (int i = index; i < this->index; i++) {
			this->arr[i] = this->arr[i + 1];
		}
		this->index--;
		return t;
	}
	
}
